package com.olive.config;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import com.olive.authentication.SmsCodeAuthenticationProvider;
import com.olive.filter.SmsCodeAuthenticationFilter;
import com.olive.filter.SmsCodeValidateFilter;
import com.olive.handler.CommonLoginFailureHandler;
import com.olive.handler.CommonLoginSuccessHandler;
import com.olive.service.impl.SmsUserDetailsServiceImpl;

@Component
public class SmsCodeSecurityConfig
		extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
	
	@Autowired
	private SmsUserDetailsServiceImpl userDetailsService;
	
	@Autowired
	private CommonLoginSuccessHandler successHandler;
	@Autowired
	private CommonLoginFailureHandler failureHandler;
	@Resource
	private SmsCodeValidateFilter smsCodeValidateFilter;
	@Override
	public void configure(HttpSecurity http) {
		SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
		smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
		smsCodeAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);
		SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
		smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
		http.addFilterBefore(smsCodeValidateFilter, UsernamePasswordAuthenticationFilter.class);
		http.authenticationProvider(smsCodeAuthenticationProvider).
				addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
	}
}

